using Senparc.Weixin.Exceptions;
using Senparc.Weixin.Open.Entities.Request;
using Senparc.Weixin.Open.Helpers;
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace Senparc.Weixin.Open
{
	public static class RequestMessageFactory
	{
		public static IRequestMessageBase GetRequestEntity(XDocument doc, PostModel postModel = null)
		{
			RequestMessageBase requestMessageBase = null;
			try
			{
				RequestInfoType requestInfoType = InfoTypeHelper.GetRequestInfoType(doc);
				switch (requestInfoType)
				{
				case RequestInfoType.component_verify_ticket:
					requestMessageBase = new RequestMessageComponentVerifyTicket();
					break;
				case RequestInfoType.unauthorized:
					requestMessageBase = new RequestMessageUnauthorized();
					break;
				default:
					throw new UnknownRequestMsgTypeException(string.Format("InfoType：{0} 在RequestMessageFactory中没有对应的处理程序！", requestInfoType), new ArgumentOutOfRangeException());
				}
				//requestMessageBase.FillEntityWithXml(doc);
			}
			catch (ArgumentException inner)
			{
				throw new WeixinException(string.Format("RequestMessage转换出错！可能是InfoType不存在！，XML：{0}", doc.ToString()), inner);
			}
			return requestMessageBase;
		}
		public static IRequestMessageBase GetRequestEntity(string xml)
		{
			return RequestMessageFactory.GetRequestEntity(XDocument.Parse(xml), null);
		}
		public static IRequestMessageBase GetRequestEntity(Stream stream)
		{
			IRequestMessageBase requestEntity;
			using (XmlReader xmlReader = XmlReader.Create(stream))
			{
				XDocument doc = XDocument.Load(xmlReader);
				requestEntity = RequestMessageFactory.GetRequestEntity(doc, null);
			}
			return requestEntity;
		}
	}
}
